const express = require('express');  // express 框架
const fs = require('fs') // 引入fs核心模块
const path = require('path');   // 引入 path 核心模块
const md5 = require('md5'); // 引入md5 加载密码
const User = require('./nodels/User');  // 封装用户文档集合 (表)
const Cart = require('./nodels/Cart')  // 购物车集合
const Coupon = require('./nodels/Coupon') // 评论集合
const Order = require('./nodels/Order') // 订单集合
const sendEmail = require('./nodels/sendEmail'); //  封装发送邮件模块
const formidable = require('formidable')
const multer  = require('multer'); // 保存图片模块
// const upload = multer({ dest: 'public/img/avatar/'}) // 文件储存路径
const storage = multer.diskStorage({
    //设置上传后文件路径，uploads文件夹会自动创建。
    destination: function (req, file, cb) {
         if (req.url === '/sendGoods' && file.fieldname == 'goods') {
           cb(null, './public/img/goods')
       } else if (req.url === '/sendGoods' && file.fieldname == 'goodsParams') {
           cb(null, './public/img/goodsparams')
       }else if (req.url === '/sendGoods' && file.fieldname == 'goodsDesc') {
           cb(null, './public/img/goodsdesc')
       }
         else if (req.url === '/sendfile') {
           cb(null, './public/img/avatar')
       }
         else if (req.url === '/editgoods') {
             if (file.fieldname == 'goods') {
                 cb(null, './public/img/goods')
             }
             if (file.fieldname == 'goodsParams') {
                 cb(null, './public/img/goodsparams')
             }
             if (file.fieldname == 'goodsDesc') {
                 cb(null, './public/img/goodsdesc')
             }
         } else if (req.url === '/addFirstSwiper') {
             cb(null, './public/img/firstSwiper')
         }else if (req.url == '/changeLogo') {
             cb(null, './public/img/logo')
         }
    },
    // 给上传文件重命名，获取添加后缀名
    filename: function (req, file, cb) {
        let fileFormat = (file.originalname).split(".");
        if (req.url === '/sendGoods' || req.url === '/editgoods' || req.url === '/addFirstSwiper') {
            cb(null, new Date().getTime() + "." + fileFormat[fileFormat.length - 1]);
        }  else if (req.url === '/sendfile') {
            cb(null, req.session.user._id + "." + fileFormat[fileFormat.length - 1]);
        }else if (req.url === '/changeLogo') {
            cb(null, 'newLogo.' + fileFormat[fileFormat.length - 1])
        }
    }
});
const upload = multer({
    storage: storage
});
const alipayBox = require('./nodels/util/alipayBox') // 封装阿里支付
const Comment = require('./nodels/Comment')


let authorityPassword = 'motherandboby'



// 工具函数
const {upDataUrlAndDelFile, getNewUrlAndFileName, appendParams} = require('./nodels/util/changeGoods')

// 导入商家模块

const Good = require('./nodels/Good') // 商品集合
const GoodsType = require('./nodels/GoodsType') // 商品类型集合
const BusinessAccount = require('./nodels/BusinessAccount') // 商家账号集合
const BaseSetUp = require('./nodels/BaseSetUp') // 商家对系统设置集合
const Notice = require('./nodels/Notice')

// 路由
const router = express.Router();

// 解决跨域问题
    router.all('*', function (req, res, next) {
        res.header("Access-Control-Allow-Origin", "http://localhost:8080");
        // res.header("Access-Control-Allow-Origin", '*');
        res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');

        res.header('Access-Control-Allow-Credentials', 'true');
        res.header("Access-Control-Allow-Headers", "X-Requested-With");
        // res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
        res.header('Access-Control-Allow-Headers', 'Content-Type');
        next();
    });
    // 加载前端页面
    router.get('/', (request, response)=> {
        response.sendFile(path.join(__dirname, 'dist', 'index.html'))
    })
    // 处理提交注册信息
    router.post('/register', (request, response)=>{
        request.body.password = md5(md5(request.body.password));

        new User(request.body).save((err)=>{
            if (err) {
                return response.status(500).json({
                    res_code: 0,
                    message: 'Server error.'
                })
            } else {
                return response.status(200).json({
                    res_code: 0,
                    message: 'success'
                })
            }
        })
    })
    // 查询邮箱是否重复
    router.get('/findEmail',(request, response)=>{
        User.findOne({
            email: request.query.email
        }, (err, data)=> {
            if (err) {
                return response.status(500).json({
                    res_code: 0,
                    message: '访问人数过多，请稍后重试'
                })
            }
            if (data) {
                return response.status(200).json({
                    res_code: 1,
                    message: '当前邮箱被注册'
                })

                } else {
                return response.status(200).json({
                    res_code: 2,
                    message: '当前邮箱可用'
                })
                }

        })
    })
    // 获取验证码
    router.get('/getCode',(request, response)=>{
        // console.log(request.query.email)
        let emailCode  = Math.random().toString().slice(-6) //验证码为6位随机数
        let email = {
            title: 'MotherAndBobyMall--邮箱验证码',
            htmlBody: '<h1>Hello!</h1><p style="font-size: 18px;color:#000;">验证码为：<u style="font-size: 16px;color:#1890ff;">'+ emailCode +'</u></p><p style="font-size: 14px;color:#666;">10分钟内有效</p>>'
        }
        let mailOptions = {
            from: '2465431331@qq.com', // 发件人地址
            to: request.query.email, // 收件人地址，多个收件人可以使用逗号分隔
            subject: email.title, // 邮件标题
            html: email.htmlBody // 邮件内容
        };
        sendEmail.send(mailOptions)
        response.status(200).json({
            key_code: emailCode
        })
    })
    // 验证登录信息
    router.post('/signIn', (request, response)=> {
        User.findOne({
            email: request.body.email,
            password: md5(md5(request.body.password))
        }, (err, data)=>{
            if (err) {
                return response.status('500').json({
                    res_code: 0,
                    message: 'Serve Busy'
                })
            }else {
                if (!data) {
                    response.status(200).json({
                        res_code: 1,
                        message: 'Email Or Password Invalid'
                    })
                }else {
                    request.session.user = data;
                    response.status(200).json({
                        res_code: 2,
                        message: 'OK',
                        userMessage: data,
                    })
                }
            }
        })
    })
    //  前端保持登录状态
    router.post('/getUser', (request, response)=> {
        if (request.session.user) {
            User.findById(request.session.user._id, (err, data)=> {
                return response.status(200).json({
                    user: data
                })
            })
        } else {
            return response.status(200).json({
                user: null
            })
        }


    })

    // 退出登录
    router.post('/signout', (request, response)=> {
        // console.log(request.session.user);
        request.session.user = null
        response.status(200).send()
    })
    // 更新用户信息
    router.post('/changeInformation', (request, response)=> {
        console.log(request.session.user);
        User.findByIdAndUpdate(request.session.user._id,request.body.config,(err, data)=> {
            if (err) {
                return response.status(500).json({
                    res_code: 0,
                    message: err.message
                })
            }else {
                return response.status(200).json({
                    res_code: 1,
                    message: 'OK'
                })
            }
        })
        // console.log(request.body.config);
        // response.send()
    })
    // 更改密码
    router.post('/changepassword', (request, response)=> {
        console.log(request.body)
        User.findOne({
            _id: request.session.user,
            password:md5(md5( request.body.config.oldpassword))
        }, (err, data)=>{
            if (err) {
                return response.status(500).json({
                    res_code: 0,
                    message: err.message
                })
            }
            if(!data) {
                return response.status(200).json({
                    res_code: 1,
                    message: '旧密码错误'
                })
            }else {
                User.findByIdAndUpdate(request.session.user._id,{
                    password: md5(md5(request.body.config.newpassword))
                },(err)=>{
                    if(err) {
                        return response.status(500).json({
                            res_code: 0,
                            message: err.message
                        })
                    }else {
                        return response.status(200).json({
                            res_code: 2,
                            message: 'OK'
                        })
                    }
                })
            }
        })

    })
    // 操作用户收货地址
    router.get('/receivingaddress', (request, response)=> {
            if (!request.session.user) {
                response.status(200).json({
                res_code: 1,
                message: ' Account number is Invalid '
            })
        }else {
            User.findById(request.session.user._id,function (err,user) {
                if (err) {
                    return response.status(500).json({
                        res_code: 0,
                        messsage: err.message
                    })
                }else {
                    user.address.push(JSON.parse(request.query.data));
                    user.markModified('address');
                    user.save((err)=>{
                        if(err) {
                            return  response.status(500).json({
                                res_code: 1,
                                message: err.message
                            })
                        }else {
                            return  response.status(200).json({
                                res_code: 2,
                                message: 'OK'
                            })
                        }
                    })
                }
            })
        }
    })
    // 更改收货地址
    router.post('/changeaddress', (request, response)=> {
        if (!request.session.user) {
            return  response.status(500).json({
                res_code: 0,
                message: ' Account number is Invalid '
            })
        }else {
           User.findById(request.session.user._id,(err, user)=>{
               if (err) {
                   return response.status(500).json({
                       res_code: 1,
                       message: err.message
                   })
               }else {
                   user.address.splice(request.body.index, 1, request.body.data);
                   user.markModified('address');
                   user.save((err)=>{
                       if(err) {
                           return response.status(500).json({
                               res_code: 1,
                               message: err.message
                           })
                       }else {
                           return  response.status(200).json({
                               res_code: 2,
                               message: 'OK'
                           })
                       }
                   })

               }
           })
        }
    })
    // 删除收货地址
    router.get('/deleaddress',(request,response)=>{
        User.findById(request.session.user._id, (err, user)=>{
            if (err) {
                return response.status(500).json({
                    res_code: 1,
                    message: err.message
                })
            }else {
                user.address.splice(request.query.data , 1);
                user.markModified('address');
                user.save((err)=>{
                    if(err) {
                        return  response.status(500).json({
                            res_code: 1,
                            message: err.message
                        })
                    }else {
                        return  response.status(200).json({
                            res_code: 2,
                            message: 'OK'
                        })
                    }
                })

            }
        })
    })
    // 用户上传图像
    router.post('/sendfile', upload.single('avatar'), (request,response)=> {
        let file = request.file;
            // console.log(file)
        // console.log(request.session,222);
        let path = `http://localhost:3000/public/img/avatar/${file.filename}`;
        User.findByIdAndUpdate(request.session.user._id,{
            avatar: path
        }, (err)=> {
            if(err) {
                return response.status(500).json({
                    res_code: 0,
                    message: err.message
                })
            }
        })
        response.json({
            res_code: 2,
            message: 'OK',
            path: path
        })
    })

    /*
    *
    *   处理商家请求
    *
    * */


    // sendGoods
    router.post('/sendGoods', upload.fields([{name: 'goods', maxCount: 99}, {name: 'goodsParams',maxCount: 99}, {name: 'goodsDesc',maxCount: 99}]), (request, respones)=>{
        let files = request.files;
        let goods = request.body;
        goods.category = goods.category.split(',')
        goods.paramsFilename = [];
        goods.params = [];
        goods.descFilename = [];
        goods.desImg = [];
        goods.goodsFilename = [];
        goods.goodsImg = [];
        if (request.body.paramTitle instanceof Array) {
            for (let i in files.goodsParams) {
                goods.paramsFilename.push(files.goodsParams[i].filename)
                goods.params.push({
                    title: request.body.paramTitle[i],
                    url: `http://localhost:3000/public/img/goodsparams/${files.goodsParams[i].filename}`
                })
            }
        } else {
            for (let i of files.goodsParams) {
                goods.paramsFilename.push(i.filename)
                goods.params.push({
                    title: request.body.paramTitle,
                    url: `http://localhost:3000/public/img/goodsparams/${i.filename}`
                })
            }
        }
        for (let i of files.goods) {
            goods.goodsFilename.push(i.filename)
            goods.goodsImg.push({url:`http://localhost:3000/public/img/goods/${i.filename}`})
        }
        for (let i of files.goodsDesc) {
            goods.descFilename.push(i.filename)
            goods.desImg.push({url: `http://localhost:3000/public/img/goodsdesc/${i.filename}`})
        }
        new Good(goods).save((err, data)=> {
            if (err) {
                respones.status(500).json({
                    res_code: 0,
                    message: err.message
                })
            } else {
                respones.status(200).json({
                    res_code: 2,
                    message: 'OK',
                    goods: data
                })
            }
        });
    })
    // 修改商品
    router.post('/editgoods', upload.fields([{name: 'goods', maxCount: 99}, {name: 'goodsParams',maxCount: 99}, {name: 'goodsDesc',maxCount: 99}]), (request, response)=> {
        let files = request.files;
        Good.findById(request.body._id, (err, data)=> {
            if (err) {
                return response.status(500).json({
                    res_code: 0,
                    message: err.message
                })
            } else {
                upDataUrlAndDelFile({
                    delUrl: request.body.delGoodsFile,
                    dataUrl: data.goodsImg,
                    dataName: data.goodsFilename,
                    path: 'goods',

                })
                if (files.goods) {
                    getNewUrlAndFileName(files.goods, data,'goods')
                }
                upDataUrlAndDelFile({
                    delUrl: request.body.delDescFile,
                    dataUrl: data.desImg,
                    dataName: data.descFilename,
                    path: 'goodsdesc',

                })
                if (files.goodsDesc) {
                    getNewUrlAndFileName(files.goodsDesc, data, 'goodsDesc')
                }
                upDataUrlAndDelFile({
                    delUrl: request.body.delGoodsParamsUrl,
                    dataUrl: data.params,
                    dataName: data.paramsFilename,
                    path: 'goodsparams',

                })
                if (files.goodsParams) {
                    appendParams(files.goodsParams, data, request.body.paramTitle)
                }
                data.name = request.body.name;
                data.category = request.body.category.split(',');
                data.isSell = request.body.isSell;
                data.price = request.body.price;
                data.describe = request.body.describe;
                data.stock = request.body.stock;
                data.save((err, data)=> {
                if (err) {
                    response.status(500).json({
                        res_code: 0,
                        message: err.message
                    })
                }else {
                    response.status(200).json({
                        res_code: 2,
                        message: 'OK',
                        goods: data
                    })
                }
            });

            }

        })
    })
    // 获取所有商品
    router.post('/getallgoods', (request, response)=> {
        Good.find({},(err, data)=> {
            if (err) {
                response.status(500).json({
                    res_code: 0,
                    message: err.message
                })
            }else {
                response.status(200).json({
                    res_code: 2,
                    message: 'OK',
                    goods: data
                })
            }
        })
    });
    // 更改商品上架状态
    router.post('/changesell', (request, response)=> {
        Good.findByIdAndUpdate(request.body.id, {
            isSell: request.body.isSell
        }, err=> {
            if (err) {
                return response.status(500).json({
                    res_code: 0,
                    message: err.message
                })
            }else {
                return response.status(200).json({
                    res_code: 2,
                    message: 'OK'
                })
            }
        })
    })
    // 删除商品
    router.post('/delgoods', (request, response)=> {
        let p1,p2,p3;
        Good.findById(request.body.id, (err, data)=> {

        })

        Good.findByIdAndRemove(request.body.id, (err, data)=> {
            p1 = new Promise((resolve, reject) => {
                data.goodsFilename.forEach(item=> {
                    fs.unlink(path.join(__dirname, 'public','img','goods', item), err=> {
                        if (err) {
                            return response.status(500).json({
                                res_code: 0,
                                message: err.message
                            })
                        } else {
                            resolve()
                        }
                    })
                })
            })
            p2 = new Promise((resolve, reject) => {
                data.paramsFilename.forEach(item=> {
                    fs.unlink(path.join(__dirname, 'public','img','goodsparams', item), err=> {
                        if (err) {
                            return response.status(500).json({
                                res_code: 0,
                                message: err.message
                            })
                        } else {
                            resolve()
                        }
                    })
                })
            })
            p3 = new Promise((resolve, reject) => {
                data.descFilename.forEach(item=> {
                    fs.unlink(path.join(__dirname, 'public','img','goodsdesc', item), err=> {
                        if (err) {
                            return response.status(500).json({
                                res_code: 0,
                                message: err.message
                            })
                        } else {
                            resolve()
                        }
                    })
                })
            })
            Promise.all([p1, p2, p3]).then(()=>{
                    response.status(200).json({
                        res_code: 2,
                        message: 'OK'
                    });
                });
        })
    })
    // 添加商品种类
    router.post('/addtype', (request, response)=> {
            GoodsType.findOne({
                value: request.body.value
            }, (err, data)=> {
                if (err) {
                    response.status(500).json({
                        res_code: 0,
                        message: err.message
                    })
                } else {
                    if (!data) {
                        new GoodsType({
                            value: request.body.value[0],
                            label: request.body.label,
                            children: [{
                                value: request.body.value[0] + 1,
                                label: request.body.title
                            }]
                        }).save((err,data)=> {
                            if (err) {
                                response.status(500).json({
                                    res_code: 0,
                                    message: err.message,
                                })
                            } else {
                                response.status(200).json({
                                    res_code: 2,
                                    message: 'Ok',
                                    data: data
                                })
                            }
                        })
                    } else {
                        data.children.push({
                            value: data.children.length + 1 + data.value,
                            label: request.body.title
                        })
                        response.status(200).json({
                            res_code: 2,
                            message: 'Ok',
                            data: data
                        })
                        data.save()
                    }
                }
            })
    })
    // 获取所有商品分类
    router.post('/getgoodstype', (request, response)=> {
        GoodsType.find({}, (err, data)=> {
            if (err) {
                response.status(500).json({
                    res_code: 0,
                    message: err.message
                })
            } else {
                response.status(200).json({
                    res_code: 2,
                    message: 'OK',
                    data: data
                })
            }
        })
    })
    // 删除商品子分类
    router.post('/deltype', (request, response)=> {
        let condition = Math.floor(request.body.value / 1000) *1000
        GoodsType.findOne({
            value: condition
        }, (err, data)=> {
            if (err) {
                response.status(500).json({
                    res_code: 0,
                    message: err.message
                })
            } else {
                let num;
                data.children.filter((item, index)=> {
                    if (item.value === request.body.value) {
                        num = index
                    }
                });
                data.children.splice(num, 1);
                data.save(err=> {
                    if (err) {
                        response.status(500).json({
                            res_code: 0,
                            message: err.message
                        })
                    } else {
                        response.status(200).json({
                            res_code: 2,
                            message: 'OK'
                        })
                    }
                })
            }
        })
    })
    // 修改商品子分类名称
    router.post('/edittype', (request, response)=> {
        GoodsType.findOne({
            value: request.body.value
        }, (err, data)=> {
            data.children.find((item)=> {
                if (item.value == request.body.code) {
                    item.label = request.body.title
                }
            })
            data.markModified('children')
                data.save(err=> {
                if (err) {
                    response.status(500).json({
                        res_code: 0,
                        message: err.message
                    })
                } else {
                    response.status(200).json({
                        res_code: 2,
                        message: 'OK'
                    })
                }
            })
        })
    })
    // 获取分类子分类
    router.post('/singlegoodstype', (request, response)=> {
        GoodsType.findOne({
            value: request.body.value
        }, (err, data)=> {
            if (err) {
                response.status(500).json({
                    res_code: 0,
                    message: err.message
                })
            } else {
                if (data) {
                   response.status(200).json({
                       res_code: 2,
                       message: 'OK',
                       data: data,
                   })
               } else {
                   response.status(200).json({
                       res_code: 1,
                       message: 'GoodsType Is Null',
                   })
               }
            }
        })
    });
    // 获取分类对应的商品
    router.post('/singlegoods', (request, response)=> {
        request.body.value = request.body.value + ''
        Good.find({
            category: {$in: [,request.body.value]}
        }, (err, data)=> {
            if (err) {
                console.log(err.message)
            }else {
               if (request.body.screen == 'sales') {
                   data.sort((firstEl, secondEl)=> secondEl.salesd - firstEl.salesd)
               }else if (request.body.screen == 'praise') {
                   data.sort((firstEl, secondEl)=> secondEl.star - firstEl.star)
               }else if (request.body.screen == 'new') {
                   data.reverse()
               }

               if (request.body.price instanceof Array) {
                   data =  data.filter(item=> item.price > request.body.price[0] &&  item.price < request.body.price[1])

               }

                let goods = null;
                if (request.body.currentPage == 1) {
                    goods = data.slice(0, 13);
                } else {
                    goods = data.slice((request.body.currentPage -1) * 12 -1, request.body.currentPage *12);
                }
                let num = data.length/12;
                if (num > Math.floor(num)) {
                    num = Math.floor(num) + 1
                }
                response.status(200).json({
                    res_code: 2,
                    message: 'ok',
                    goods: goods,
                    totalPage: num * 10
                })
            }
        })
    });
    // 获取单个商品
    router.post('/getdetail', (request, response)=> {
        Good.findById(request.body.id, (err, data)=> {
            if (err) response.status(500).json({res_code:0, message: err.message})
            response.status(200).json({
                res_code: 2,
                message: 'OK',
                goods: data
            })
        })
    });
    // 收藏商品
    router.post('/collection', (request, response)=> {
        Good.findById(request.body.id,(err,data)=> {
            if (err) {
                return response.status(500).json({
                    res_code: 0,
                    message: err.message
                })
            }else {
                if (request.body.isCollection) {
                    data.favorites--;
                    User.findByIdAndUpdate(request.session.user._id,{
                        $pull: {favorites: request.body.id}
                    },(err)=> {
                        if (err) {
                            console.log(err.message)
                        } else {
                            return response.status(200).json({
                                res_code: 2,
                                message: "ok"
                            })
                        }
                    })
                } else {
                    data.favorites++;
                    User.findByIdAndUpdate(request.session.user._id,{
                        $push: {favorites: request.body.id}
                    },(err)=> {
                        if (err) {
                            console.log(err.message)
                        } else {
                            return response.status(200).json({
                                res_code: 2,
                                message: "ok"
                            })
                        }
                    })
                }
                data.save()
            }
        });
    })
    // 通过id 获取商品(仅用于用户中心页面使用)
    router.post('/idtogoods', (request, response)=> {
        let resArr = [];
        new Promise(resolve => {
            request.body.idArr.forEach((item, index)=> {
                Good.findById(item, (err, data)=> {
                    if (err) {
                        return response.status(500).json({
                            res_code: 0,
                            message: err.message
                        })
                    }
                    let obj;
                    if (data) {
                         obj = {
                            imgUrl: data.goodsImg[0],
                            name: data.name,
                            price: data.price
                        }
                        resArr.push(obj)
                    }

                    if (index === request.body.idArr.length -1) {
                        resolve(resArr)
                    }
                })
            })
        }).then((res)=> {
            return  response.status(200).json({
                res_code: 2,
                message: 'Ok',
                show: res
            })
        })

    });
    // 添加足迹商品
    router.post('/addfootfrint',(request, response)=> {
        User.findById(request.session.user._id, (err, data)=> {
            if (err) {
                return response.status(500).json({
                    res_code: 0,
                    message: err.message
                })
            }
            let num = data.footFrint.indexOf(request.body.id);
            if (num != -1) {
                data.footFrint.splice(num, 1);
            }
            data.footFrint.unshift(request.body.id);
            if (data.footFrint.length > 50) {
                data.footFrint.splice(data.footFrint.length - 1, 1)
            }
            data.markModified('footFrint');
            data.save(err=> {
                if (err) {
                    return response.status(500).json({
                        res_code: 0,
                        message: err.message
                    })
                } else {
                    return response.status(200).json({
                        res_code: 2,
                        message: 'ok'
                    })
                }
            })
        })
    });
    // 删除用户浏览记录
    router.post('/delfootfrint', (request, response)=> {
        User.findByIdAndUpdate(request.session.user._id, {
            $pull: {footFrint: request.body.id}
        },err=> {
            if (err) {
                return response.status(500).json({
                    res_code: 0,
                    message: err.message
                })
            }else {
                return response.status(200).json({
                    res_code: 2,
                    messsage: 'OK'
                })
            }
        })
    });
    // 添加购物车
    router.post('/addCart', (request, response)=> {
        Cart.findOne({
            userId: request.body.userId
        },(err, data)=> {
            if (err) return response.status(500).json({
                res_code: 0,
                message: err.message
            })
            if (data) {
                let num;
                data.carts.find((item, index)=> {
                    if (item.id == request.body.id && item.params == request.body.params) {
                        return num = index
                    }
                })
                if (num>=0) {
                    data.carts[num].num ++
                } else {
                    data.carts.push({
                        num: request.body.num,
                        id: request.body.id,
                        showUrl: request.body.showUrl,
                        params: request.body.params,
                        name: request.body.name,
                        price: request.body.price,
                        isChoose: true,
                        stock: request.body.stock,
                        isCom: false
                    })
                }
                data.markModified('carts');
                data.save(err=> {
                    if (err) {
                        return response.status(500).json({
                            res_code: 0,
                            message: err.message
                        })
                    }
                    return response.status(200).json({
                        res_code: 2,
                        message: '添加成功',
                        index: num
                    })
                })
            } else {
                new Cart({
                    userId: request.body.userId,
                    carts: [{
                        num: request.body.num,
                        id: request.body.id,
                        showUrl: request.body.showUrl,
                        params: request.body.params,
                        name: request.body.name,
                        price: request.body.price,
                        isChoose: true,
                        stock: request.body.stock,
                        isCom: false
                    }]
                }).save(err=> {
                    if (err) return response.status(500).json({
                        res_code: 0,
                        message: err.message
                    })
                    return response.status(200).json({
                        res_code: 2,
                        message: '添加成功'
                    })
                })
            }
        })
    });
    // 获取购物车商品
    router.post('/getCart', (request, response)=> {
        Cart.findOne({
            userId: request.body.userId
        }, (err, data)=> {
            if (err) return response.status(500).json({
                res_code: 0,
                message: err.message
            })
            if (data) {
                return response.status(200).json({
                    res_code: 2,
                    cart: data.carts
                })
            } else {
                return response.status(200).json({
                    res_code: 2,
                    cart: []
                })
            }
        })
    });
    // 获取优惠券
    router.post('/getCoupon', (request, response)=> {
        Coupon.find({
            userId: request.body.userId
        }, (err, data)=> {
            if (err) {
                console.log(err.message);
                return response.status(500).json({
                    res_code: 0,
                    coupons: []
                })
            } else {
                return response.status(200).json({
                    res_code: 2,
                    message: 'OK'
                })
            }
        })
    })
    // 删除购物车商品
    router.post('/delCartGoods', (request, response)=> {
        console.log(request.body)
        Cart.findOne({
            userId: request.session.user._id
        },(err, data)=> {
            let num;
            if (err) return response.status(500).json({
                res_code: 0,
                message: err.message
            })
            data.carts.filter((item, index)=> {
                if (item.id == request.body.goodsId && item.params == request.body.params) {
                    return num = index
                }
            })
            data.carts.splice(num, 1);
            data.markModified('carts');
            data.save(err=> {
                if (err) return response.status(500).json({
                    res_code: 0,
                    message: err.message
                })
                return response.status(200).json({
                    res_code: 2,
                    message: '删除成功',
                    num: num
                })
            })
        })
    });
    // 操作购物车
    router.post('/editCartGoods', (request, response)=> {
        Cart.findOne({
            userId: request.session.user._id
        }, (err, data)=> {
            if (err) return response.status(500).json({
                res_code: 0,
                message: err.message
            })
            data.carts.filter(item=> {
                if (item.id == request.body.id && item.params == request.body.params) {
                    if (request.body.plus) {
                        if (item.stock > item.num) {
                            item.num ++
                        }else {
                            return response.status(200).json({
                                res_code: 1,
                                message: '超出库存数量'
                            })
                        }
                    }else {
                        if (item.num > 1) {
                            item.num ++
                        } else {
                            return response.status(200).json({
                                res_code: 1,
                                message: '购物车内商品不可少于1'
                            })
                        }
                    }
                }
            })
            data.markModified('carts')
            data.save(err=> {
                if (err) return response.status(500).json({
                    res_code: 0,
                    message: err.message
                })
                return response.status(200).json({
                    res_code: 2,
                    message: 'ok'
                })
            })
        })
    })

    router.post('/pay', (request, response)=> {
           let sumPrice = request.body.cartGoods.reduce((total, currentValue)=> {
                return total + currentValue.num * currentValue.price
            },0).toString()
        sumPrice = (sumPrice * request.body.discount - request.body.integral / 100).toFixed(2)
        alipayBox.pay(sumPrice).then(res=> {
            request.body.sumPrice = sumPrice
            request.session.order = request.body
            return response.status(200).json({
                url: res
            })
        })
    })
    // 处理支付成功逻辑 但是此处有问题，未来跳转地址需要其他地址！！！！！！！！！！！
    router.get('/callpay', (request, response)=> {
        // console.log(request.session.order)
            if (request.session.order.discountId) {
                Coupon.remove({
                    value: request.session.order.discountId
                })
            }
            request.session.order.cartGoods.forEach(item=> {
                Good.update({
                    _id: item.id
                }, {
                    $inc: {salesd: 1, stock: (item.num * -1)}
                }).then(res=> {
                    console.log('我是更新商品')
                })
            })
            Cart.update({
                userId: request.session.user._id
            }, {
                $pull: {carts: {$in: request.session.order.cartGoods}}
            }).then(res=> {
                console.log('我是购物车')
            })
            User.findById(request.session.user._id, (err, data)=> {
                data.luckNumber ++;
                data.integral = data.integral - request.session.order.integral + parseInt( request.session.order.sumPrice)
                data.markModified('luckNumber')
                data.markModified('integral')
                data.save(err=> {
                    if (err) {
                        console.log(err.message)
                        return
                    };
                    response.redirect('http://localhost:8080/luckDraw')  // 后期必改点
                })
            });
            new Order({
            goodsMessage: request.session.order.cartGoods,
            address: request.session.order.address,
            userId: request.session.user._id
        }).save(err=> {
            if (err) {
                console.log(err.message)
            }else {
                request.session.order = null
            }
        })
    })
    // 获取订单
    router.post('/getOrder', (request, response)=> {
        Order.find({
            userId: request.body.id
        }, (err, data)=> {
            if (err) return response.status(500).json({
                res_code: 0,
                message: err.message
            })
            return response.status(200).json({
                res_code: 2,
                orders: data
            })
        })
    })
    // 抽奖
    router.post('/luck', (request, response)=> {
        User.findById(request.session.user._id,(err, data)=> {
            data.luckNumber --
            data.markModified('luckNumber')
            data.save(err=> {
                if (parseInt(request.body.discount) > 0) {
                    new Coupon({
                        userId: request.session.user._id,
                        label: request.body.discount,
                        coupon: request.body.discount.substr(0, request.body.discount.length - 1)
                    }).save(err=> {
                        return response.status(200)
                    })
                }else  {
                    return response.status(200)
                }
            })
        })
    })
    // 注册超级管理员
    router.post('/Superregister', (request, resonse)=> {
        if (request.body.key != authorityPassword) {
            return resonse.status(200).json({
                res_code: 1,
                message: '权限密码不正确'
            })
        }
        new BusinessAccount({
            isSuper: true,
            nickname: '超级管理员',
            account: request.body.account,
            password: md5(md5(request.body.password)),
            jurisdiction: ['客服','商品管理','系统设置','订单管理']
        }).save(err=> {
            if (err) return resonse.status(500).json({
                res_code: 0,
                message: err.messagem,
                type: 'error'
            })
            return resonse.status(200).json({
                res_code: 2,
                message: '注册成功',
                type: 'success'
            })
        })

    })
    // 检测账号是否被注册
    router.post('/inspect',(request, response)=> {
        BusinessAccount.findOne({
            account: request.body.account
        }, (err,data)=> {
            if (request.body.edit) {
                if(data && data.account != request.body.edit) {
                    return response.status(200).json({
                        res_code: 1,
                    })
                }else {
                    return response.status(200).json({
                        res_code: 2,
                    })
                }
            }else {
                if(data) {
                    return response.status(200).json({
                        res_code: 1,
                    })
                }else {
                    return response.status(200).json({
                        res_code: 2,
                    })
                }
            }

        })
    })
    // 商家登录
    router.post('/businessSignIn', (request, response)=> {
        BusinessAccount.findOne({
            account: request.body.account,
            password: md5(md5(request.body.password))
        },(err, data)=> {
            if (err) {
                return response.status(200).json({
                    res_code: 0,
                    message: err.message,
                    type: 'error'
                })
            }
            if (data) {
                request.session.businessUser = data
                return response.status(200).json({
                    res_code: 2,
                    message: '登录成功',
                    type: 'success',
                    businessUser: data
                })
            } else {
                return response.status(200).json({
                    res_code: 1,
                    message: 'User Or Passord Invalid',
                    type: 'warning',
                })
            }
        })
    })
    // 获取登录商家信息
    router.post('/getBusinessUser', (request, response)=> {
        if (request.session.businessUser) {
            BusinessAccount.findById(request.session.businessUser._id, (err, data)=> {
                if (err) return response.status(500).json({
                    res_code: 0,
                    message: err.message
                })
                return response.status(200).json({
                    res_code: 2,
                    message: 'ok',
                    businessUser: data
                })
            })
        }else {
            return response.status(200).json({
                res_code: 2,
                message: '未登录',
                businessUser: {jurisdiction: []}
            })
        }
    })
    // 商家退出
    router.post('/businessSignOut',(request, response)=> {
        request.session.businessUser = null
        response.status(200).send()
    })
    // 获取所有账户
    router.post('/findAllAccount', (request, response)=> {
        BusinessAccount.find({},(err, data)=> {
            if (err) return response.status(500).json({
                res_code: 0,
                message: err.message,
                type: 'error'
            })
            return response.status(200).json({
                res_code: 2,
                message: 'OK',
                accounts: data
            })
        })
    })
    // 注册普通用户
    router.post('/addAccount', (request, response)=> {
        request.body.password = md5(md5(request.body.password))
        new BusinessAccount(request.body).save(err=> {
            if (err) {
                return response.status(500).json({
                    res_code: 0,
                    message: err.message,
                    type: 'error'
                })
            }
            return response.status(200).json({
                res_code: 2,
                message: '添加成功',
                type: 'success'
            })
        })
    })
    // 更改商家用户信息
    router.post('/changeAccount',(request, response)=> {
        BusinessAccount.findByIdAndUpdate(request.body._id,{
            isSuper: request.body.isSuper,
            jurisdiction: request.body.jurisdiction,
            account: request.body.account,
            nickname: request.body.nickname,
            tel: request.body.tel,
            password: md5(md5(request.body.password))
        },(err)=> {
            if (err) return response.status(500).json({
                res_code: 0,
                message: err.message,
                type: 'error'
            })
            return response.status(200).json({
                res_code: 2,
                message: '更改成功',
                type: 'success'
            })
        })
    })
    // 删除商家账户
    router.post('/delAccount', (request, response)=> {
        BusinessAccount.findByIdAndRemove(request.body.id, (err)=> {
            if (err) return response.status(500).json({
                res_code: 0,
                message: err.message,
                type: 'error'
            })
            return response.status(200).json({
                res_code: 2,
                message: '删除成功',
                type: 'success'
            })
        })
    })
    // 商家获取全部订单
    router.post('/getBusinessOrders', (request, response)=> {
        Order.find({},(err, data)=> {
            if (err) return response.status(200).json({
                res_code: 0,
                message: err.message,
                type: 'error'
            })
            return response.status(200).json({
                res_code: 2,
                message: '加载数据成功',
                type: 'success',
                data: data
            })
        })
    })
    // 添加物流单号
    router.post('/addDelivery', (request, response)=> {
        Order.findByIdAndUpdate(request.body.id, {
            delivery: request.body.delivery,
            lssue: true
        }, (err)=> {
            if (err) return response.status(500).json({
                res_code: 0,
                message: err.message,
                type: 'error'
            })
            return response.status(200).json({
                res_code: 2,
                message: '添加成功',
                type: 'success'
            })
        })
    })
    // 上传一级轮播图
    router.post('/addFirstSwiper',upload.single('firstSwiper'), (request, response)=> {
        let file = request.file
        BaseSetUp.findOne({},(err, data)=> {
            if (err) return response.status(500).json({
                res_code: 0,
                message: err.message,
                type: 'error'
            })
            console.log()
            if (data) {
                data.firstSwiper.push({
                    imgUrl: `http://localhost:3000/public/img/firstSwiper/${file.filename}`,
                    fileName: file.filename,
                    url: request.body.url,
                    id: Date.now()
                })
                data.markModified('firstSwiper')
                data.save(()=> response.status(200).json({
                    res_code: 2,
                    message: '添加成功',
                    type: 'success'
                }))
            }else {
                new BaseSetUp({
                   firstSwiper: {
                       imgUrl: `http://localhost:3000/public/img/firstSwiper/${file.filename}`,
                       fileName: file.filename,
                       url: request.body.url,
                       id: Date.now()
                   }
                }).save(()=> response.status(200).json({
                    res_code: 2,
                    message: '添加成功',
                    type: 'success'
                }))
            }
        })
    })
    // 获取设置数据
    router.get('/getBaseSetData', (request, response)=> {
        let query = JSON.parse(request.query.data);
        BaseSetUp.findOne({}, (err, data)=> {
            if (err) return response.status(500).json({
                res_code: 0,
                message: err.message,
                type: 'error'
            })
            let obj = {
                res_code: 2,
                message: 'ok',
            }
            // console.log(data.firstSwiper)
            if (!data) {
                obj.data = []
            }else if (query.type == 1) {
                obj.data = data.firstSwiper
            }
            return response.status(200).json(obj)
        })
    })
    // 删除第一个轮播图
    router.post('/delFirstSwiper', (request, response)=> {
        fs.unlink(path.join(__dirname,'public','img','firstSwiper', request.body.filename),(err => {
            BaseSetUp.findOne({}, (err, data)=> {
                let num;
                data.firstSwiper.forEach((item, index)=> {
                    if (item.fileName == request.body.filename) {
                        num = index
                    }
                })
                data.firstSwiper.splice(num, 1);
                data.markModified('firstSwiper')
                data.save(()=> response.status(200).json({
                    res_code: 2,
                    message: '删除成功',
                    type: 'success'
                }))
            })
        }))
    })
    // 获取系统品牌名称及logo
    router.get('/brand', (request, response)=> {
        BaseSetUp.findOne({}, (err, data)=> {
            if (err) return response.status(500).json({
                res_code: 0,
                message: '请求失败',
                type: 'error'
            })

            if (data) {
                return response.status(200).json({
                    res_code: 2,
                    message: '请求成功',
                    type: 'success',
                    data: {
                        brand: data.brand,
                        logoUrl: data.logoUrl,
                        test: '1'
                    }
                })
            }else {
                return response.status(200).json({
                    res_code: 2,
                    message: '请求成功',
                    type: 'success',
                    data: {
                        brand: '母婴销售系统',
                        logoUrl: 'http://localhost:3000/public/img/logo/logo.png',
                        test: '2'
                    }
                })
            }


        })
    })
    // 改变logo
    router.post('/changeLogo', upload.single('logo'), (request, response)=> {
        BaseSetUp.findOne({}, (err, data)=> {
            if (err) return response.status(500).json({
                res_code: 0,
                message: err.message,
                type: 'error'
            })
            if (data) {
                data.logoUrl = `http://localhost:3000/public/img/logo/${request.file.filename}`
                data.save()
            }else {
                new BaseSetUp({
                    logoUrl: `http://localhost:3000/public/img/logo/${request.file.filename}`
                }).save()
            }
            return  response.status(200).json({
                res_code: 2,
                message: '上传成功',
                type: 'success'
            })
        })
    })
    // 改变系统品牌名称
    router.post('/changeBrand', (request, response)=> {
        BaseSetUp.findOne({}, (err, data)=> {
            if (err) return response.status(500).json({
                res_code: 0,
                message: err.message,
                type: 'error'
            })
            if (data) {
               data.brand = request.body.brand
                data.save()
            }else {
                new BaseSetUp({
                    brand: request.body.brand
                }).save()
            }
            return  response.status(200).json({
                res_code: 2,
                message: '更新成功',
                type: 'success'
            })
        })
    })
    // 添加公告
    router.post('/addNotice', (request, response)=> {
        new Notice(request.body).save(err=> {
            if (err) return response.status(500).json({
                res_code: 0,
                message: err.message,
                type: 'error'
            })
            return response.status(200).json({
                res_code: 2,
                message: '添加成功',
                type: 'success'
            })
        })
    })
    // 获取公告
    router.post('/getNotice', (request, response)=> {
        Notice.find({}, (err, data)=> {
            if (err) return response.status(500).json({
                res_code: 0,
                message: err.message,
                type: 'error'
            })
            return response.status(200).json({
                res_code: 2,
                message: '获取成功',
                type: 'success',
                data: data
            })
        })
    })
    // 通过名字获取商品id
    router.post('/searchName', (request, response)=> {
        Good.find({
            name: {$regex: request.body.searchName}
        }, (err, data)=> {
            if (err) return  response.status(500).json({
                res_code: 0,
                message: err.message,
                type: 'error'
            })
            let arr = []
            data.forEach(item=> {
                arr.push({
                    id: item._id,
                    name: item.name
                })
            })
            return response.status(200).json({
                res_code: 2,
                message: '查询成功',
                type: 'success',
                goods: arr
            })
        })
    })
    // 添加推荐类
    router.post('/addRec', (request, response) => {
        request.body.id = Date.now()
        BaseSetUp.findOne({}, (err, data)=> {
            if (err) return response.status(500).json({
                res_code: 0,
                message: err.message,
                type: 'error'
            })
            if (data) {
                console.log(data)
                data.recommends.push(request.body)
                data.markModified('recommends')
                data.save(err=> {
                    if (err) return  response.status(500).json({
                        res_code: 0,
                        message: err.message,
                        type: 'error'
                    })
                    return response.status(200).json({
                        res_code: 2,
                        message: '添加成功',
                        type: 'success'
                    })
                })
            }else {
                new BaseSetUp({
                    recommends: [request.body]
                }).save(err=> {
                    if (err) return  response.status(500).json({
                        res_code: 0,
                        message: err.message,
                        type: 'error'
                    })
                    return response.status(200).json({
                        res_code: 2,
                        message: '添加成功',
                        type: 'success'
                    })
                })
            }
        })
    })
    // 获取推荐类
    router.get('/getRec', (request, response)=> {
        BaseSetUp.findOne({}, (err, data)=> {
            if (err) return  response.status(500).json({
                res_code: 0,
                message: err.message,
                type: 'error'
            })
            if (data) {
                return  response.status(200).json({
                    res_code: 2,
                    message: '成功',
                    type: 'success',
                    data: data.recommends
                })
            } else {
                return  response.status(200).json({
                    res_code: 2,
                    message: '成功',
                    type: 'success',
                    data: []
                })
            }
        })
    })
    //  删除推荐类
    router.post('/delRec', (request, response)=> {
        BaseSetUp.findOne({},(err, data)=> {
            let num;
            data.recommends.forEach((item, index)=> {
                if (item.id == request.body.id) {
                    return num = index
                }
            })
            data.recommends.splice(num, 1)
            data.markModified('recommends')
            data.save(err=> {
                if (err) return response.status(500).json({
                    res_code: 0,
                    message: err.message,
                    type: 'error'
                })
                return response.status(200).json({
                    res_code: 2,
                    message: '删除成功',
                    type: 'success'
                })
            })
        })
    })
    // 获取首页轮播数据
    router.get('/getSwiper', (request, response)=> {
        BaseSetUp.findOne({}, (err, data)=> {
            if (err)    return response.status(500).json({
                res_code: 0,
                message: err.message,
                type: 'error'
            })

            if (data) {
                return response.status(200).json({
                    res_code: 2,
                    message: 'ok',
                    type: 'success',
                    swiper: data.firstSwiper
                })
            }else {
                return response.status(200).json({
                    res_code: 2,
                    message: 'ok',
                    type: 'success',
                    swiper: []
                })
            }
        })
    })
    // 获取首页推荐类
    router.get('/getWeek', (request, response)=> {
        BaseSetUp.findOne({}, (err, data)=> {
            if (err) return response.status(500).json({
                res_code: 0,
                message: err.message,
                type: 'error'
            })
            if (!data) {
                return response.status(200).json({
                    res_code: 2,
                    message: 'ok',
                    type: 'success',
                    recommends: []
                })
            } else {
                if (data.recommends.length == 0) {
                    return response.status(200).json({
                        res_code: 2,
                        message: 'ok',
                        type: 'success',
                        recommends: []
                    })
                } else {
                    let recommends = []
                    data.recommends.forEach((item, index)=> {
                                 let obj = {goods: []}
                                 obj.title = item.title
                                 Good.find({
                                     _id: {$in: item.goodsId}
                                 }).then(res=> {
                                     obj.goods = res
                                     recommends.push(obj)
                                     if (recommends.length == data.recommends.length) {
                                         return response.status(200).json({
                                             res_code: 2,
                                             message: 'ok',
                                             type: 'success',
                                             recommends,
                                         })
                                     }
                                 })
                        })


                }
            }

        })
    })
    // 导航栏搜索功能
    router.post('/nameToGoods', (request, response)=> {
        if (request.body.name == '') {
            return response.status(200).json({
                type: 'success',
                goods: []
            })
        }else {
            Good.find({
                name: {$regex: request.body.name}
            }).then(res=> {
                return response.status(200).json({
                    type: 'success',
                    goods: res
                })
            })
        }

    })
    // 添加评论
    router.post('/addComment', (request, response)=> {
        Order.findOne({
            _id: request.body.id
        }, async (err, data)=> {
           data.goodsMessage.forEach((item, index)=> {
               if (item.id == request.body.goods) {
                   item.isCom = true
               }
           })
            data.markModified('goodsMessage')
            await data.save()
            await new Comment({
                userId: request.session.user,
                goodsId: request.body.goods,
                message: request.body.comments.message,
                star: request.body.comments.rate
            }).save()
            await  Good.findOne({
                _id: request.body.goods
            }, (err, data)=> {
                Comment.find({
                    goodsId: request.body.goods
                }).then(res=> {
                    data.star = (request.body.comments.rate + data.star) / res.length
                    data.save(err=> {
                        if (err) return response.status(500).json({
                            res_code: 0,
                            message: err.message,
                            type: 'error'
                        })
                        return response.status(200).json({
                            res_code: 2,
                            message: '评论成功',
                            type: 'success'
                        })
                    })
                })
            })
        })
    })
    // 用户获取评论信息
    router.get('/getComments', (request, response)=> {
        Comment.find({
            userId: request.session.user._id
        }).then(res=> {
           return response.status(200).json({
               res_code: 2,
               message: 'OK',
               comments: res,
               type: 'success'
           })
        }).catch(err=> {
            return response.status(500).json({
                res_code: 0,
                message: err.message,
                type: 'error'
            })
        })
    })
    // 评论模块，通过商品Id获取第一张图片和名字
    router.post('/getGoodsStar', (request, response)=> {
        // console.log(request.body)
        Good.findOne({
            _id: request.body.id
        }).then(res=> {
            return response.status(200).json({
                res_code: 2,
                type: 'success',
                message: 'Ok',
                data: {
                    name: res.name,
                    url: res.goodsImg[0].url
                }
            })
        }).catch(err=> {
            return response.status(500).json({
                res_code: 0,
                message: err.message,
                type: 'error'
            })
        })
    })
    // 删除评论
    router.post('/delComment', async (request, response)=> {
        await Comment.findByIdAndRemove(request.body.id)
        await Good.findOne({
            _id: request.body.goodsId
        }, (err, data)=> {
            Comment.find({
                goodsId: request.body.goods
            }).then(res=> {
                let sum = res.reduce((total, item)=> {
                    return total + item.star
                },0)
                if (res.length == 0) {
                    data.star = 0
                }else {
                    data.star = sum / res.length
                }
                data.markModified('star')
                data.save(err=> {
                    if (err) console.log(err.message)
                    return response.status(200).json({
                        res_code: 2,
                        message: '删除成功',
                        type: 'success'
                    })
                })
            })
        })

    })
    // 用户获取优惠券
    router.get('/getCoupon', (request, response)=> {
        Coupon.find({
            userId: request.session.user._id
        }).then(res=> {
            return response.status(200).json({
                res_code: 2,
                message: 'OK',
                type: 'success',
                coupons: res
            })
        }).catch(err=> {
            return response.status(500).json({
                res_code: 0,
                message: err.message,
                type: 'error',
            })
        })
    })
    // 获取当前商品评价状态
    router.post('/hasCom', (request, response)=> {
        Comment.find({
            goodsId: request.body.id
        }).then(res=> {
            let num = res.reduce((total, item)=> {
                return total + item.star
            },0)
            return response.status(200).json({
                res_code: 2,
                message: 'OK',
                type: 'success',
                comMsg: {
                    averageStar: num / res.length,
                    num: res.length
                }
            })
        })
    })
    // 获取所有评论
    router.post('/getGoodsComments', (request, response)=> {
        Comment.find({
            goodsId: request.body.id
        }).then(res=> {
            return response.status(200).json({
                res_code: 2,
                message: 'OK',
                type: 'success',
                comments: res
            })
        }).catch(err=> {
            return response.status(500).json({
                res_code: 0,
                message: err.message,
                type: 'error'
            })
        })
    })
    // 获取用户头像加名字
    router.post('/getUserMsg', (requset, response)=> {
        User.findOne({
            _id: requset.body.id
        }).then(res=> {
            return response.status(200).json({
                res_code: 2,
                message: 'OK',
                type: 'success',
                user: {
                    avatar: res.avatar,
                    nickname: res.nickname
                }
            })
        })
    })
   // 获取评论的商品star
    router.post('/getCommentsStar', (request, response)=> {
        Good.findOne({
            _id: request.body.id
        }).then(res=> {
            return response.status(200).json({
                res_code: 2,
                message: 'OK',
                type: 'success',
                star: res.star
            })
        })
    })
module.exports = router;